import babelpolyfill from 'babel-polyfill'

import Vue from 'vue'//引入vue，根据package.json中依赖名字引入的
import App from './App'//引入根组件

//import './assets/theme/theme-green/index.css'

import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
import routes from './routes'//引入路由

//引入自定义vue指令
import '@/common/js/permissions'


//注释mock.js
// import Mock from './mock'
// Mock.bootstrap();
import 'font-awesome/css/font-awesome.min.css'

//引入elementUi
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

//配置Axios的全局属性和基础路径
import axios from "axios";
Vue.prototype.$http=axios;
//每次发送axios请求之前都会加上这个基础路径
axios.defaults.baseURL="http://localhost:8080";
//操.....defaults

//引入百度地图
import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, {
  /* Visit http://lbsyun.baidu.com/apiconsole/key for details about app key. */
  ak: '4RWmQlKQkGgdOUuDqaVbkjBg2IY3sjh0'
})

//==axios的【前置拦截器】拦截调用后端的请求====================//
axios.interceptors.request.use(res=>{
  let token = localStorage.getItem("token");
  //如果登陆了，并且没有过期
  if(token){
    //将token的值设置到请求头
    res.headers["token"] = token;
  }
  return res;
},error => {
  Promise.reject(error)
})
//======================axios的前置拦截器【拦截调用后端的请求】====================//

//===axios的【后置拦截器】处理后台登录拦截的结果====================//
axios.interceptors.response.use(res => {
  //后端响应的是没有登录的信息  =>双重校验，防止执行因为后端异常报错的false
  if (false === res.data.success && ("noLogin" === res.data.msg || "timeOut" === res.data.msg)) {
    //跳转登录页面会在发送login请求时删除本地浏览器数据
    // localStorage.removeItem("token");
    // localStorage.removeItem("logininfo");
    // localStorage.removeItem("permissions");
    // localStorage.removeItem("menus");
    //跳转登陆页面
    router.push({path: '/login'});
  }
  return res;
},error => {
  Promise.reject(error)
})
//======================axios的后置拦截器【处理后台登录拦截的结果】====================//

//NProgress.configure({ showSpinner: false });

//通过路由规则定义路由
const router = new VueRouter({
  //router：router
  routes//等价于上面那一句，根据同名原则匹配
})

//【路由拦截拦截器】:拦截不发送ajax请求的的资源；404，login，register
router.beforeEach((to, from, next) => {
  //如果访问的是登陆页面
  if (to.path == '/login' || to.path == '/register') {
    localStorage.removeItem("token");
    localStorage.removeItem("logininfo");
    localStorage.removeItem("permissions");
    localStorage.removeItem("menus");
    next();
  }else {//访问的不是登陆和注册页面；访问受限资源
    let logininfo = JSON.parse(localStorage.getItem("logininfo"));
    if(logininfo){//有登陆信息
      next();
    }else{//没有登陆信息
      next({path:'/login'})
    }
  }

})

//router.afterEach(transition => {
//NProgress.done();
//});

new Vue({
  //el: '#app',
  //template: '<App/>',
  router,//引入路由-匹配规则 ；简写方式：router：router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')//这个vue实例要挂载到index.html中



//【动态路由】
//处理页面刷新动态路由失效问题
//在Login.vue页面登录成功之后刷新一下本地的路由缓存防止动态菜单还是上一个登录用户的菜单【location.reload();】
initIndexRouters();
function initIndexRouters(){
  if(!localStorage.menus){
    return;
  }
  //防止重复配置路由：5就是main.js中路由的个数 - 如果你的静态路由是6个这里要写成6
  if(router.options.routes.length>5){
    return;
  }
  let menus = localStorage.getItem('menus');
  menus = JSON.parse(menus);
  let tempRouters = [];
  menus.forEach(menu=>{
    let indexRouter = {
      path: '/',
      iconCls: menu.icon,
      name: menu.name,
      component: resolve => require(['@/views/Home'], resolve),
      children: []
    }
    menu.children.forEach(cMenu=>{
      let cr = {
        path: cMenu.url,
        name: cMenu.name,
        component: resolve => require(['@/views/'+cMenu.component], resolve)
      }
      indexRouter.children.push(cr)
    })
    tempRouters.push(indexRouter)
    router.options.routes.push(indexRouter)
  })
  //动态路由配置
  router.addRoutes(tempRouters);
}